package bancosys.tec.rtm.impl.diagnostician;

import java.io.Serializable;
import java.net.URL;
import java.net.URLClassLoader;

import jmine.tec.annotations.Unmodifiable;
import bancosys.tec.rtm.diagnostician.AbstractDiagnostician;
import bancosys.tec.rtm.diagnostician.DiagnosisBean;

/**
 * @author takeshi
 */
@Unmodifiable
public class ClassLoaderDiagnostician extends AbstractDiagnostician implements Serializable {

    /**
     * {@inheritDoc}
     */
    public String getName() {
        return "Classloader";
    }

    /**
     * @param bean the {@link DiagnosisBean}
     * @param contextClassLoader {@link ClassLoader}
     */
    private void extractClassloaderInfo(DiagnosisBean bean, ClassLoader contextClassLoader) {
        if (contextClassLoader != null) {
            bean.addDescription("-> classloader: " + contextClassLoader + "\n");
            if (contextClassLoader instanceof URLClassLoader) {
                URLClassLoader url = (URLClassLoader) contextClassLoader;
                final URL[] urls = url.getURLs();
                if (urls != null) {
                    for (URL url2 : urls) {
                        bean.addDescription(url2.toString() + "\n");
                    }
                }
            } else {
                bean.addDescription("ClassLoader não é um URLClassLoader");
            }
            extractClassloaderInfo(bean, contextClassLoader.getParent());
        }
    }

    /**
     * {@inheritDoc}
     * 
     * @see bancosys.tec.rtm.diagnostician.AbstractDiagnostician#fillDiagnosisBean(bancosys.tec.rtm.diagnostician.DiagnosisBean)
     */
    @Override
    protected boolean fillDiagnosisBean(DiagnosisBean bean) throws Exception {
        bean.addDescription("Visible classloaders: \n");
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        extractClassloaderInfo(bean, contextClassLoader);
        extractClassloaderInfo(bean, this.getClass().getClassLoader());
        bean.addDescription("end of visible classloaders\n");
        return true;
    }
}
